<?php
/**
 * Create by chang
 * Date 2020/1/7
 * Time 9:24
 * 商品
 */
namespace app\admin\service;

use app\common\model\GoodsSpec;
use app\common\service\BaseService;
use app\common\service\StatusService;
use think\Db;
use think\Exception;

class GoodsService extends BaseService {
	
	public function editSpec($goodsId, $specs) {
		$specModel = new GoodsSpec();
		//查找原来的规格
		$oldSpecs = $specModel->getSpecsByGoodsId($goodsId);
		
		//规格ID和名称组成的数组
		$oldName = [];
		
		//要删除的
		if($oldSpecs) {
			foreach ($oldSpecs as $oldSpec) {
				$oldName[$oldSpec['id']] = $oldSpec['name'];
			}
		}
		
		//更新的
		$editList = [];
		
		//添加的
		$insert = [];
		if($specs) {
			foreach ($specs as $spec) {
				$spec['goods_id'] = $goodsId;
				$spec['status'] = StatusService::STATUS_NORMAL;
				$spec['update_time'] = time();
				
				if($spec['id']) {
					//编辑更新的
					$editList[] = $spec;
				} else if(in_array($spec['name'], $oldName)) {
					//添加了一个跟已经删除同名的规格
					$index = array_search($spec['name'], $oldName);
					$spec['id'] = $index;
					$editList[] = $spec;
				} else {
					unset($spec['id']);
					$spec['create_time'] = time();
					//新添加的规格
					$insert[] = $spec;
				}
			}
		}
		
		if($insert || $editList) {
			try {
				$model = new GoodsSpec();
				
				if($insert) {
					$addRes = $model->insertAll($insert);
					if(!$addRes) {
						throw new Exception('添加规格出错');
					}
				}
				
				if($editList) {
					$editRes = $model->saveAll($editList);
					if($editRes === false) {
						throw new Exception('更新规格出错'.$model->getError());
					}
				}
				
				return true;
			} catch (Exception $e) {
				$this->error = $e->getMessage();
				return false;
			}
			
		}
		return true;
	}
	
}
